package TAIC.util;

import java.io.File;
import java.io.PrintStream;
import java.util.Scanner;

public class Average {
	public static void main ( String arg [] ) {
		try {
			int iter = 20 ; 
			if ( arg.length < 1 ) { 
				System.out.println ( "Please input the name of config file") ;
				return ; 
			}
			
			Scanner configScanner = new Scanner ( new File ( arg [ 0 ]  )) ; 
			String prefix = configScanner.next () ; 
			
			//int number = configScanner.nextInt() ;
			int dimI = 0 , dimJ = 0  ; 
			double result [][][] = null ; 
			double result1 [][][] = null ; 
			int number = 0 ;
			while (configScanner.hasNext() ) {
				number ++ ; 
				String no = configScanner.next() ;
				Scanner scanner  = new Scanner ( new File ( prefix + no + ".txt" )) ;
				int x = scanner.nextInt()  ;
				int y = scanner.nextInt() ; 
				iter = scanner.nextInt() ;
				if ( result == null ) {
					dimI = x ; 
					dimJ = y ;
					result = new double [iter ][ dimI ][ dimJ ] ;
					result1 = new double [iter ][ dimI ][ dimJ ] ;
				}
				for ( int i = 0 ; i < dimI ; i ++ )
					for ( int j = 0 ; j < dimJ ; j ++ )
						for ( int r = 0 ; r < iter ; r ++ ) {
							result1 [ r ][ i ][ j ] = scanner.nextDouble() ;
							result [ r ][ i ][ j ] += result1 [ r ][ i ][ j ] ;
						}				
				if ( scanner.hasNext() ) throw ( new Exception( "the iteration parameter is not right" )) ;
				PrintStream fout = new PrintStream ( new File ( prefix + "result_" + no + ".txt" )) ; 
				for ( int r = 0 ; r < iter ; r ++ ) {
					for ( int i = 0 ; i < dimI ; i ++ ) {
						for ( int j = 0 ; j < dimJ - 1 ; j ++ ) fout.print( result1[r][i][j] + "\t") ;
						fout.print ( result1[r][i][dimJ-1] + "\r\n" ) ;
					}
					fout.print ("\r\n") ;
				}
				fout.close() ;
			}
			

			PrintStream fout = new PrintStream ( new File ( prefix+ "result.txt" )) ; 
			for ( int r = 0 ; r < iter ; r ++ ) {
				for ( int i = 0 ; i < dimI ; i ++ ) {
					for ( int j = 0 ; j < dimJ - 1 ; j ++ ) fout.print( result[r][i][j]/ number + "\t") ;
					fout.print ( result[r][i][dimJ-1] / number + "\r\n" ) ;
				}
				fout.print ("\r\n") ;
			}
			fout.close() ;
			
		}catch ( Exception e ){ 
			e.printStackTrace() ; 
		}
	}
}
